package banners

import (
	"context"
	"goods_bff/controller"
	"goods_bff/forms"
	"goods_bff/goods_proto"
	"goods_bff/pkg"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	comment := pkg.Comment()
	rsp, err := comment.BannerList(context.Background(), &goods_proto.Empty{})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}

	result := make([]interface{}, 0)
	for _, value := range rsp.Data {
		reMap := make(map[string]interface{})
		reMap["id"] = value.Id
		reMap["index"] = value.Index
		reMap["image"] = value.Image
		reMap["url"] = value.Url

		result = append(result, reMap)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": result,
	})
}

func New(c *gin.Context) {
	bannerForm := forms.BannerForm{}
	if err := c.ShouldBindJSON(&bannerForm); err != nil {
		controller.ReturnErrorJson(err, c)
		return
	}
	comment := pkg.Comment()
	rsp, err := comment.CreateBanner(context.Background(), &goods_proto.BannerRequest{
		Index: int32(bannerForm.Index),
		Url:   bannerForm.Url,
		Image: bannerForm.Image,
	})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}

	response := make(map[string]interface{})
	response["id"] = rsp.Id
	response["index"] = rsp.Index
	response["url"] = rsp.Url
	response["image"] = rsp.Image

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": response,
	})
}

func Update(c *gin.Context) {
	bannerForm := forms.BannerForm{}
	if err := c.ShouldBindJSON(&bannerForm); err != nil {
		controller.ReturnErrorJson(err, c)
		return
	}

	id := c.Query("id")
	idInt, _ := strconv.Atoi(id)
	comment := pkg.Comment()
	_, err := comment.UpdateBanner(context.Background(), &goods_proto.BannerRequest{
		Id:    int32(idInt),
		Index: int32(bannerForm.Index),
		Url:   bannerForm.Url,
	})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": nil,
	})
}

func Delete(c *gin.Context) {
	id := c.Query("id")
	idInt, _ := strconv.Atoi(id)
	comment := pkg.Comment()
	_, err := comment.DeleteBanner(context.Background(), &goods_proto.BannerRequest{Id: int32(idInt)})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": nil,
	})
}
